package com.oreilly.ez.fileserver.base;


import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {



    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Object handleEmptyBodyException(Exception e){

        e.printStackTrace();
        return R.err("对象为空或者解析失败");
    }


    /**
     * validation Exception
     *
     * @param e
     * @return R
     */
    @ExceptionHandler({ConstraintViolationException.class, MethodArgumentNotValidException.class, BindException.class})
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleBodyValidException(Exception e) {

        e.printStackTrace();
        StringBuffer message = new StringBuffer();
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                if (!StringUtils.isEmpty(message)) {
                    message.append("," + item.getMessage());
                } else {
                    message.append(item.getMessage());
                }
            }
        }
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exs = (MethodArgumentNotValidException) e;
            // 按需重新封装需要返回的错误信息
            // 解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
            for (FieldError error : exs.getBindingResult().getFieldErrors()) {
                if (!StringUtils.isEmpty(message)) {
                    message.append(",参数异常：" + error.getField() + error.getDefaultMessage());
                } else {
                    message.append("参数异常：" + error.getField() + error.getDefaultMessage());
                }
            }
        }

        if (e instanceof BindException) {
            BindException exs = (BindException) e;
            for (FieldError error : exs.getBindingResult().getFieldErrors()) {
                if (!StringUtils.isEmpty(message)) {
                    message.append(",参数异常：" + error.getField() + error.getDefaultMessage());
                } else {
                    message.append("参数异常：" + error.getField() + error.getDefaultMessage());
                }
            }
        }
        return R.err( message.toString());
    }



    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandle(HttpServletRequest request, Exception e){
        e.printStackTrace();
//        Map<String, Object> map = new HashMap<>();
//
//        map.put("code", -1);
//        map.put("message", e.getMessage());
//        return map;
        return R.err(e.getMessage());
    }
}
